/*
 * ============================================================================
 *
 *       Filename:  common.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015年01月15日 16时03分28秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <errno.h>

#include <netinet/tcp.h>
#include <netdb.h>

#include "common.h"

void fllush_stdin()
{
	int c;
	while ( (c = getchar()) != '\n' && c != EOF ) { }
}

char *getmacstr(unsigned char *mac)
{
	char *macstr = Malloc(MACSTR_LEN);
	if(!macstr) return NULL;
	sprintf(macstr, "%02x:%02x:%02x:%02x:%02x:%02x",
		(mac)[0],(mac)[1],(mac)[2],
		(mac)[3],(mac)[4],(mac)[5]); 		
	return macstr;
}

int tcp_alive(int sock)
{
	int optval = 1;
	int optlen = sizeof(optval);
	if(setsockopt(sock, SOL_SOCKET,
			SO_KEEPALIVE, &optval, optlen) < -1) {
		sys_warn("Set tcp keepalive failed: %s\n",
			strerror(errno));
		return 0;
	}

	optval = 1;
	if(setsockopt(sock, SOL_TCP,
			TCP_KEEPCNT, &optval, optlen) < -1) {
		sys_warn("Set tcp_keepalive_probes failed: %s\n",
			strerror(errno));
		return 0;
	}

	optval = 5;
	if(setsockopt(sock, SOL_TCP,
			TCP_KEEPIDLE, &optval, optlen) < -1) {
		sys_warn("Set tcp_keepalive_time failed: %s\n",
			strerror(errno));
		return 0;
	}

	optval = 5;
	if(setsockopt(sock, SOL_TCP,
			TCP_KEEPINTVL, &optval, optlen) < -1) {
		sys_warn("Set tcp_keepalive_intvl failed: %s\n",
			strerror(errno));
		return 0;
	}

	return 1;
}
